/**============================================================================
 *
 * Author: luo1o1o1o 
 *
 * QQ: 330240995, PHONE: 17600071321
 *
 * Last modified: 2021-06-10 09:53
 *
 * Filename: loginChecks.js
 *
 * Description: 登录验证的中间件
 *
 ============================================================================**/

const { ErrorModel } = require('../model/ResModel')
const { loginCheckFailInfo } = require('../model/ErrorInfo')
/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-10 10:12
 * @desc: API登录验证
 */
async function loginChecks(ctx, next) {
    // 已登录
    if (ctx.session && ctx.session.userInfo) {
        await next()
        return
    }
    // 未登录
    ctx.body = new ErrorModel(loginCheckFailInfo)
}

/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-10 10:12
 * @desc: 页面登录验证
 */
async function loginRedirect(ctx, next) {
    // 已登录
    if (ctx.session && ctx.session.userInfo) {
        await next()
        return
    }
    // 未登录
    const curUrl = ctx.url
    ctx.redirect('/login?url=' + encodeURIComponent(curUrl))
}

module.exports = {
    loginChecks,
    loginRedirect,
}
